<template>
  <div class="mod-demo-echarts">
    <el-alert title="提示：" type="warning" :closable="false">
      <div slot-scope="description">
        <p class="el-alert__description">
          1.
          此Demo只提供ECharts官方使用文档，入门部署和体验功能。具体使用请参考：http://echarts.baidu.com/index.html
        </p>
      </div>
    </el-alert>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div id="J_chartLineBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card>
          <div id="J_chartBarBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card>
          <!-- <el-input
            v-model="input"
            class="skuName-input"
            placeholder="请输入干货id或干货名称"
          ></el-input> -->
          <el-autocomplete
            class="skuName-input"
            v-model="skuName"
            :fetch-suggestions="querySearch"
            placeholder="干货名称"
            :trigger-on-focus="true"
          ></el-autocomplete>
          <el-button @click="initChartPie">查询</el-button>
          <div id="J_chartPieBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <!-- <el-col :span="12">
        <el-card>
          <div id="J_chartScatterBox" class="chart-box"></div>
        </el-card>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
  data() {
    return {
      chartLine: null,
      chartBar: null,
      chartPie: null,
      chartScatter: null,
      input: "9",
      skuName: "井冈山辣椒 1斤",
      skuNameList: []
    };
  },
  mounted() {
    this.initChartLine();
    this.initChartBar();
    this.initChartPie();
    // this.initChartScatter();
    this.getSkuInfos();
  },
  activated() {
    // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
    if (this.chartLine) {
      this.chartLine.resize();
    }
    if (this.chartBar) {
      this.chartBar.resize();
    }
    if (this.chartPie) {
      this.chartPie.resize();
    }
    if (this.chartScatter) {
      this.chartScatter.resize();
    }
  },
  methods: {
    // 折线图
    initChartLine() {
      var option;
      this.$http({
        // url: this.$http.adornUrl("/product/skuinfo/get/allSkuInfo"),
        url: this.$http.adornUrl("/product/skuinfo/get/seven/five/drygoods"),
        method: "get"
        // params: this.$http.adornParams({})
      }).then(({ data }) => {
        // console.log(data);
        if (data && data.code === 0) {
          if (data.result != null) {
            var list = data.result;
            console.log(list);
            var nowDay = list.nowDay;
            var oldOneDay = list.oldOneDay;
            var oldTwoDay = list.oldTwoDay;
            var oldThreeDay = list.oldThreeDay;
            var oldFourDay = list.oldFourDay;
            // console.log(nowDay);
            //当天sku干货名称
            var nowSkuNames = nowDay.map(item => {
              return item.skuName;
            });
            // console.log(skuIds);
            //sku干货销量
            var nowSaleCounts = nowDay.map(item => {
              return item.saleCount;
            });
            //上一天sku干货名称
            var oldOneDaySaleCounts = oldOneDay.map(item => {
              return item.saleCount;
            });
            //上两天sku干货名称
            var oldTwoDaySaleCounts = oldTwoDay.map(item => {
              return item.saleCount;
            });
            //上三天sku干货名称
            var oldThreeDaySaleCounts = oldThreeDay.map(item => {
              return item.saleCount;
            });
            //上四天sku干货名称
            var oldFourDaySaleCounts = oldFourDay.map(item => {
              return item.saleCount;
            });

            option = {
              title: {
                text: "SKU干货销量分析"
              },
              tooltip: {
                trigger: "item",
                axisPointer: {
                  type: "line"
                }
                // formatter: function(params) {
                //   // console.log(params);
                //   // console.log(skuNames);
                //   return (
                //     // "干货id： " +
                //     // params[0].name +
                //     // "干货名： " +
                //     // skuNames.get(params[0].name) +
                //     "销量： " + params[0].value
                //   );
                // }
              },
              legend: {
                data: ["当天", "前一天", "前两天", "前三天", "前四天"]
              },
              grid: {
                left: "3%",
                right: "4%",
                bottom: "3%",
                containLabel: true
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              xAxis: {
                type: "category",
                boundaryGap: false,
                data: nowSkuNames,
                axisLabel: {
                  //x轴文字的配置
                  show: true,
                  interval: 0, //使x轴文字显示全
                  textStyle: {
                    color: "rgba(51, 51, 51)"
                  },
                  formatter: function(params) {
                    var newParamsName = "";
                    var paramsNameNumber = params.length;
                    var provideNumber = 3; //一行显示几个字
                    var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                    if (paramsNameNumber > provideNumber) {
                      for (var p = 0; p < rowNumber; p++) {
                        var tempStr = "";
                        var start = p * provideNumber;
                        var end = start + provideNumber;
                        if (p == rowNumber - 1) {
                          tempStr = params.substring(start, paramsNameNumber);
                        } else {
                          tempStr = params.substring(start, end) + "\n";
                        }
                        newParamsName += tempStr;
                      }
                    } else {
                      newParamsName = params;
                    }
                    return newParamsName;
                  }
                }
              },
              yAxis: {
                type: "value"
              },
              series: [
                {
                  name: "当天",
                  type: "line",
                  // stack: "总量",
                  data: nowSaleCounts,
                  smooth: true
                },
                {
                  name: "前一天",
                  type: "line",
                  // stack: "总量",
                  data: oldOneDaySaleCounts,
                  smooth: true
                },
                {
                  name: "前两天",
                  type: "line",
                  // stack: "总量",
                  data: oldTwoDaySaleCounts,
                  smooth: true
                },
                {
                  name: "前三天",
                  type: "line",
                  // stack: "总量",
                  data: oldThreeDaySaleCounts,
                  smooth: true
                },
                {
                  name: "前四天",
                  type: "line",
                  // stack: "总量",
                  data: oldFourDaySaleCounts,
                  smooth: true
                }
              ],
              //解决大数据展示问题
              dataZoom: {
                type: "slider",
                width: "100",
                zoomLock: true,
                startValue: 0,
                endValue: 10
              }
            };
            this.chartLine.setOption(option);
          }
        } else {
        }
      });
      this.chartLine = echarts.init(document.getElementById("J_chartLineBox"));
      window.addEventListener("resize", () => {
        this.chartLine.resize();
      });
    },
    // 柱状图
    initChartBar() {
      var option;
      this.$http({
        // url: this.$http.adornUrl("/product/skuinfo/get/allSkuInfo"),
        url: this.$http.adornUrl("/product/skuinfo/get/two/year/attentions"),
        method: "get"
        // params: this.$http.adornParams({})
      }).then(({ data }) => {
        console.log(data, "柱状图");
        if (data && data.code == 0) {
          if (data.result != null) {
            var list = data.result;
            var tF = list.tF;
            var fS = list.fS;
            //sku干货id
            var skuNames = tF.map(item => {
              return item.skuName;
            });

            //20-40 sku干货关注量
            var tFAttentionCounts = tF.map(item => {
              return item.attentionCount;
            });
            //40-60 sku干货关注量
            var fSAttentionCounts = fS.map(item => {
              return item.attentionCount;
            });
            option = {
              title: {
                text: "SKU干货关注量分析",
                top: 20,
                textStyle: {
                  color: "black"
                }
              },
              tooltip: {
                trigger: "axis",
                axisPointer: {
                  type: "shadow"
                }
                // formatter: function(params) {
                //   // console.log(params);
                //   // console.log(skuNames);
                //   return (
                //     // "干货id： " +
                //     // params[0].name +
                //     // "<br>干货名： " +
                //     // skuNames.get(params[0].name) +
                //     "关注量： " + params[0].value
                //   );
                // }
              },
              legend: {
                data: ["20-40岁", "40-60岁"]
              },
              grid: {
                left: "3%",
                right: "4%",
                bottom: "3%",
                containLabel: true
              },
              xAxis: [
                {
                  type: "category",
                  data: skuNames,
                  splitLine: {
                    show: false
                  },
                  axisLabel: {
                    //x轴文字的配置
                    show: true,
                    interval: 0, //使x轴文字显示全
                    textStyle: {
                      color: "rgba(51, 51, 51)"
                    },
                    formatter: function(params) {
                      var newParamsName = "";
                      var paramsNameNumber = params.length;
                      var provideNumber = 3; //一行显示几个字
                      var rowNumber = Math.ceil(
                        paramsNameNumber / provideNumber
                      );
                      if (paramsNameNumber > provideNumber) {
                        for (var p = 0; p < rowNumber; p++) {
                          var tempStr = "";
                          var start = p * provideNumber;
                          var end = start + provideNumber;
                          if (p == rowNumber - 1) {
                            tempStr = params.substring(start, paramsNameNumber);
                          } else {
                            tempStr = params.substring(start, end) + "\n";
                          }
                          newParamsName += tempStr;
                        }
                      } else {
                        newParamsName = params;
                      }
                      return newParamsName;
                    }
                  }
                }
              ],
              yAxis: [
                {
                  type: "value"
                }
              ],
              series: [
                {
                  name: "20-40岁",
                  type: "bar",
                  data: tFAttentionCounts
                },
                {
                  name: "40-60岁",
                  type: "bar",
                  data: fSAttentionCounts
                }
              ],
              //解决大数据展示问题
              dataZoom: {
                type: "slider",
                width: "100",
                zoomLock: true,
                startValue: 0,
                endValue: 10
              }
            };
            this.chartBar.setOption(option);
          }
        } else {
          console.log("出错了");
        }
      });

      this.chartBar = echarts.init(document.getElementById("J_chartBarBox"));
      window.addEventListener("resize", () => {
        this.chartBar.resize();
      });
    },

    // 饼状图
    initChartPie() {
      this.$http({
        url: this.$http.adornUrl(
          "/product/spucomment/get/sku/commentStatus/" + this.skuName
        ),
        method: "get",
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        var option;
        if (data && data.code == 0 && data.data != null) {
          console.log(data);
          // 定义使用的颜色数组
          const COLORS = [
            "#c23531",
            "#2f4554",
            "#61a0a8",
            "#d48265",
            "#91c7ae",
            "#749f83"
          ];
          option = {
            backgroundColor: "#2c343c",
            title: {
              text: "指定SKU干货的评论状态",
              left: "center",
              top: 20,
              textStyle: {
                color: "#ccc"
              }
            },
            tooltip: {
              trigger: "item",
              formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            visualMap: {
              show: false,
              min: 80,
              max: 600,
              inRange: {
                colorLightness: [0, 1]
              }
            },
            series: [
              {
                name: data.data.spuName,
                type: "pie",
                radius: "55%",
                center: ["50%", "50%"],
                data: [
                  { value: data.data.oneStar, name: "1星" },
                  { value: data.data.twoStar, name: "2星" },
                  { value: data.data.threeStar, name: "3星" },
                  { value: data.data.fourStar, name: "4星" },
                  { value: data.data.fiveStar, name: "5星" }
                ].sort(function(a, b) {
                  return a.value - b.value;
                }),
                roseType: "radius",
                label: {
                  normal: {
                    textStyle: {
                      color: "rgba(255, 255, 255, 255)"
                    }
                  }
                },
                labelLine: {
                  normal: {
                    lineStyle: {
                      color: "rgba(255, 255, 255, 0.3)"
                    },
                    smooth: 0.2,
                    length: 10,
                    length2: 20
                  }
                },
                itemStyle: {
                  normal: {
                    // color: "#c23531",
                    color: item => {
                      return COLORS[item.dataIndex % COLORS.length];
                    },
                    shadowBlur: 200,
                    shadowColor: "rgba(0, 0, 0, 0.5)"
                  }
                },
                animationType: "scale",
                animationEasing: "elasticOut",
                animationDelay: function(idx) {
                  return Math.random() * 200;
                }
              }
            ]
          };
        }

        this.chartPie = echarts.init(document.getElementById("J_chartPieBox"));
        this.chartPie.setOption(option);
        window.addEventListener("resize", () => {
          this.chartPie.resize();
        });
      });
    },
    /* 饼状图备份
    initChartPie() {
      var option = {
        backgroundColor: "#2c343c",
        title: {
          text: "指定干货的评论状态",
          left: "center",
          top: 20,
          textStyle: {
            color: "#ccc"
          }
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        visualMap: {
          show: false,
          min: 80,
          max: 600,
          inRange: {
            colorLightness: [0, 1]
          }
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "55%",
            center: ["50%", "50%"],
            data: [
              { value: 335, name: "1星" },
              { value: 310, name: "2星" },
              { value: 274, name: "3星" },
              { value: 235, name: "4星" },
              { value: 400, name: "5星" }
            ].sort(function(a, b) {
              return a.value - b.value;
            }),
            roseType: "radius",
            label: {
              normal: {
                textStyle: {
                  color: "rgba(255, 255, 255, 0.3)"
                }
              }
            },
            labelLine: {
              normal: {
                lineStyle: {
                  color: "rgba(255, 255, 255, 0.3)"
                },
                smooth: 0.2,
                length: 10,
                length2: 20
              }
            },
            itemStyle: {
              normal: {
                color: "#c23531",
                shadowBlur: 200,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function(idx) {
              return Math.random() * 200;
            }
          }
        ]
      };
      this.chartPie = echarts.init(document.getElementById("J_chartPieBox"));
      this.chartPie.setOption(option);
      window.addEventListener("resize", () => {
        this.chartPie.resize();
      });
    },
    */

    // 散点图
    initChartScatter() {
      this.$http({
        url: this.$http.adornUrl(
          "/member/membercollectsku/get/comnsume/attentionCount/relation"
        ),
        method: "get"
        // params: this.$http.adornParams({})
      }).then(({ data }) => {
        if (data && data.code == 0) {
          if (data.data != null) {
            var list = data.data;
            console.log(list);
            //消费额与关注量关系模型
            var arr2021 = new Array();
            var arr2022 = new Array();
            list.map(item => {
              if (item.relationTime == "2021") {
                var temp = new Array();
                temp.push(item.expenditure);
                temp.push(item.attentionCount);
                temp.push(100000000);
                temp.push(item.memberName);
                temp.push(item.relationTime - 0);

                arr2021.push(temp);
              } else {
                var temp = new Array();
                temp.push(item.expenditure);
                temp.push(item.attentionCount);
                temp.push(100000000);
                temp.push(item.memberName);
                temp.push(item.relationTime - 0);
                arr2022.push(temp);
              }
            });
            console.log(arr2021);
            console.log(arr2022);
            var option = {
              backgroundColor: new echarts.graphic.RadialGradient(
                0.3,
                0.3,
                0.8,
                [
                  { offset: 0, color: "#f7f8fa" },
                  { offset: 1, color: "#cdd0d5" }
                ]
              ),
              title: {
                text: "2022与2021年每个人的消费额和关注量"
              },
              legend: {
                right: 10,
                data: ["2021", "2022"]
              },
              xAxis: {
                splitLine: {
                  lineStyle: {
                    type: "dashed"
                  }
                }
              },
              yAxis: {
                splitLine: {
                  lineStyle: {
                    type: "dashed"
                  }
                },
                scale: true
              },
              series: [
                {
                  name: "2021",
                  data: arr2021,
                  type: "scatter",
                  symbolSize: function(data) {
                    return Math.sqrt(data[2]) / 5e2;
                  },
                  label: {
                    emphasis: {
                      show: true,
                      formatter: function(param) {
                        return param.data[3];
                      },
                      position: "top"
                    }
                  },
                  itemStyle: {
                    normal: {
                      shadowBlur: 10,
                      shadowColor: "rgba(120, 36, 50, 0.5)",
                      shadowOffsetY: 5,
                      color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                        { offset: 0, color: "rgb(251, 118, 123)" },
                        { offset: 1, color: "rgb(204, 46, 72)" }
                      ])
                    }
                  }
                },
                {
                  name: "2022",
                  data: arr2022,
                  type: "scatter",
                  symbolSize: function(data) {
                    return Math.sqrt(data[2]) / 5e2;
                  },
                  label: {
                    emphasis: {
                      show: true,
                      formatter: function(param) {
                        return param.data[3];
                      },
                      position: "top"
                    }
                  },
                  itemStyle: {
                    normal: {
                      shadowBlur: 10,
                      shadowColor: "rgba(25, 100, 150, 0.5)",
                      shadowOffsetY: 5,
                      color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                        { offset: 0, color: "rgb(129, 227, 238)" },
                        { offset: 1, color: "rgb(25, 183, 207)" }
                      ])
                    }
                  }
                }
              ]
            };
            this.chartPie = echarts.init(
              document.getElementById("J_chartScatterBox")
            );
            this.chartPie.setOption(option);
            window.addEventListener("resize", () => {
              this.chartPie.resize();
            });
          }
        }
      });
    },
    //下拉列表显示所有的供货商信息
    querySearch(queryString, cb) {
      var skuNameList = this.skuNameList;
      var results = queryString
        ? skuNameList.filter(this.createFilter(queryString))
        : skuNameList;
      // 调用 callback 返回建议列表的数据
      console.log(results);
      cb(results);
    },
    createFilter(queryString) {
      return sku => {
        return sku.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    //获取sku信息
    getSkuInfos() {
      this.$http({
        url: this.$http.adornUrl("/product/skuinfo/list"),
        method: "get",
        params: this.$http.adornParams({
          page: 1,
          limit: 50000
        })
      }).then(({ data }) => {
        console.log(1111);
        console.log(data, 1111);
        this.skuNameList = data.page.list.map(item => {
          return { value: item.skuName };
        });
      });
    }
  }
};
</script>

<style lang="scss">
.mod-demo-echarts {
  > .el-alert {
    margin-bottom: 10px;
  }
  > .el-row {
    margin-top: -10px;
    margin-bottom: -10px;
    .el-col {
      padding-top: 10px;
      padding-bottom: 10px;
    }
  }
  .chart-box {
    min-height: 400px;
  }
  .skuName-input {
    width: 240px;
    margin-bottom: 20px;
  }
}
</style>
